<?php

namespace App\Http\Controllers\Article;

use App\Http\Controllers\BaseController;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;

class CategoryController extends BaseController
{
    public function index()
    {
        $categories = DB::table('article_categories')
            ->where('status',1)
            ->where('type',2)
            ->orderBy('sort')
            ->get(['id','name','parent_id']);

        if ($categories->isEmpty()){
            return response()->json(['code' => 1, 'data' => [], 'msg' => '获取成功']);
        }

        $categoryList = $this->getCategoryTree($categories);


        return $this->success($categoryList);
    }


    /**
     * 递归获取分类
     * */
    private function getCategoryTree($categories)
    {

        $items = array();
        foreach ($categories as $value) {
            $items[$value->id] = $value;
        }
        $tree = array();
        foreach ($items as $key => $item) {
            if (isset($items[$item->parent_id])) {
                $items[$item->parent_id]->child[] = &$items[$key];
            } else {
                $tree[] = &$items[$key];
            }
        }

        return $tree;
    }


}
